<template>
  <div class="no-check-area">
    <c-table-box class="area" checkbox hide-func :table-row-key="tableRowKeyFun" :click-row-selection="false" :data="tableData" :table-span-method="spanMethod" :table-config="tableConfig" @selection-change="selectionChange">
      <template #btn>
        <AddArea style="margin-right:10px;" :filters-raw="filtersRaw" @on-change="changeHandle" />
        <AddSeries style="margin-right:10px;" :sel-data="selections" @on-change="changeSeriesHandle" />
        <c-button type="primary" @click="removeHandle">删除</c-button>
        <!-- <c-button type="primary">导入</c-button> -->
        <!-- <c-button type="primary">导出</c-button> -->
      </template>
    </c-table-box>
  </div>
</template>
<script>
import AddArea from './addArea'
import AddSeries from './addSeries'
import { otherFiltersItem, deepClone } from '@/utils'
import { getUnSeriesByAccId } from '@/api/check'
import typeCode from './typeCode'
const finished = ['Q014', 'Q015']
export default {
  name: 'NoCheckArea',
  components: {
    AddArea,
    AddSeries
  },
  data() {
    return {
      tableConfig: {
        interfacePath: '',
        pageFlag: false,
        setting: [
          {
            prop: 'areaName',
            label: '所属区域'
          },
          {
            prop: 'spaceName',
            label: '所属空间',
            render: (h, row) => {
              return h('c-single-dialog', {
                props: {
                  value: row.configSpacestyleId,
                  label: row.spaceName,
                  props: { label: 'spaceName', value: 'id' }
                },
                attrs: {
                  focusQuery: true,
                  config: {
                    title: '所属空间',
                    width: '600px',
                    interfacePath: '/slm-admin/api/v1/configSpaceStyle/page',
                    method: 'post',
                    filtersRaw: [
                      otherFiltersItem('enable', '1', '=')
                    ],
                    paramsRaw: {},
                    setting: [
                      { prop: 'spaceCode', title: '编码', width: 80 },
                      { prop: 'spaceName', title: '名称', width: 200 }
                    ]
                  }
                },
                on: {
                  change: v => {
                    this.$set(row, 'spaceCode', v.spaceCode)
                    this.$set(row, 'spaceName', v.spaceName)
                    this.$set(row, 'configSpacestyleId', v.id)
                    this.setValueByConfigAreaId(row, { spaceCode: v.spaceCode }, { spaceName: v.spaceName }, { configSpacestyleId: v.id })
                    this.clearSeries(row)
                  }
                }
              })
            }
          },
          {
            prop: 'acceptArea',
            label: '验收面积',
            render: (h, row) => {
              // if (!row.seriesEdit) {
              //   return h('span', '')
              // }
              return h('c-input-number', {
                props: {
                  placeholder: '请输入验收面积',
                  clearable: true,
                  value: row.acceptArea,
                  float: true
                },
                on: {
                  input: v => {
                    this.$set(row, 'acceptArea', v)
                  },
                  change: (v) => {
                    // if (!/^(\d+\.)*\d*$/.test(v)) {
                    //   this.$message.error('只能输入数字！')
                    //   this.$set(row, 'acceptArea', 0)
                    // }
                    // if (v.includes('.')) {
                    //   v = v.replace(/^(\d+\.\d{2})\d+$/, '$1')
                    //   this.$set(row, 'acceptArea', v)
                    // }
                    this.setValueByConfigAreaId(row, { acceptArea: v })
                  }
                }
              })
            }
          },
          {
            prop: 'acceptDesc',
            label: '验收说明',
            render: (h, row) => {
              if (row.seriesEdit) {
                return h('span', '')
              }
              return h('el-input', {
                props: {
                  placeholder: '请输入验收说明',
                  clearable: true,
                  value: row.acceptDesc
                },
                on: {
                  input: v => {
                    this.$set(row, 'acceptDesc', v)
                  },
                  change: (v) => {
                    this.setValueByConfigAreaId(row, { acceptDesc: v })
                  }
                }
              })
            }
          },
          {
            prop: 'seriesName',
            label: '系列名称',
            render: (h, row) => {
              const filtersRaw = [
                otherFiltersItem('spaceCode', row.spaceCode, '=')
              ]
              const tc = typeCode[row.areaCode]
              if (tc !== undefined) {
                filtersRaw.push(otherFiltersItem('typeCode', tc, '='))
              }
              return h('c-single-dialog', {
                props: {
                  value: row.configProgramSeriesId,
                  label: row.seriesName,
                  props: { label: 'seriesName', value: 'configProgramSeriesId' }
                },
                attrs: {
                  focusQuery: true,
                  disabled: !row.configSpacestyleId,
                  config: {
                    title: '系列名称',
                    width: '600px',
                    interfacePath: '/slm-admin/api/v1/acceptAreaSeriesDetail/getSeries',
                    method: 'post',
                    paramField: 'seriesName',
                    filtersRaw,
                    // paramsRaw: { spaceCode: row.spaceCode },
                    setting: [
                      { prop: 'seriesCode', title: '编码', width: 80 },
                      { prop: 'seriesName', title: '名称', width: 200 },
                      { prop: 'typeName', title: '系列类型', width: 200 }
                    ]
                  }
                },
                on: {
                  input: v => {
                    this.$set(row, 'configProgramSeriesId', v)
                  },
                  change: v => {
                    if (this.validateRepetition(row, v)) {
                      this.$nextTick(() => {
                        this.$set(row, 'configProgramSeriesId', '')
                        this.$set(row, 'seriesCode', '')
                        this.$set(row, 'seriesName', '')
                        this.$set(row, 'styleCode', '')
                        this.$set(row, 'styleName', '')
                      })
                      this.$message.error('同一个空间不能有重复的系列！')
                      return
                    }
                    this.$set(row, 'seriesCode', v.seriesCode)
                    this.$set(row, 'seriesName', v.seriesName)
                    this.$set(row, 'styleCode', v.styleCode)
                    this.$set(row, 'styleName', v.styleName)
                    this.$set(row, 'configProgramSeriesId', v.configProgramSeriesId)
                  }
                }
              })
            }
          },
          {
            prop: 'styleName',
            label: '所属专区'
          },
          {
            prop: 'actualOutpicArea',
            label: '实际出图面积'
          }
          // {
          //   prop: 'acceptArea',
          //   label: '验收面积'
          // }
        ]
      },
      tableData: [],
      selections: []
    }
  },
  computed: {
    filtersRaw() {
      const t = this.tableData.map(e => {
        return otherFiltersItem('areaCode', e.areaCode, '<>')
      })
      t.push(otherFiltersItem('enable', 1, '='))
      return t
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 同一个空间不能有重复的系列
    validateRepetition(row, s, newAdd) {
      let rows = []
      if (!newAdd) {
        rows = this.tableData.filter(e => {
          return e.areaCode === row.areaCode && e.configProgramSeriesId !== '' && e.configProgramSeriesId !== undefined && (e.id !== row.id || e.id === undefined) && e.keyIndex !== row.keyIndex
        })
      } else {
        rows = this.tableData.filter(e => {
          return e.areaCode === row.areaCode && e.configProgramSeriesId !== '' && e.configProgramSeriesId !== undefined
        })
      }
      return rows.some(e => e.configProgramSeriesId === s.configProgramSeriesId)
    },
    // 按区域id设置值
    setValueByConfigAreaId(row, ...args) {
      for (const item of this.tableData) {
        if (row.areaCode === item.areaCode) {
          for (const a of args) {
            const [k, v] = Object.entries(a)[0]
            this.$set(item, k, v)
          }
        }
      }
    },
    // 区域变动清空系列
    clearSeries(row) {
      for (const item of this.tableData) {
        if (row.areaCode === item.areaCode) {
          this.$set(item, 'configProgramSeriesId', '')
          this.$set(item, 'seriesCode', '')
          this.$set(item, 'seriesName', '')
          this.$set(item, 'styleCode', '')
          this.$set(item, 'styleName', '')
        }
      }
    },
    // 处理数据
    handlerData(data) {
      const t = {}
      for (const item of data) {
        const key = item.areaCode
        if (t[key] === undefined) {
          t[key] = []
        }
        // 设置默认值
        item.acceptArea ? '' : item.acceptArea = 0
        item.acceptSeriesArea ? '' : item.acceptSeriesArea = 0
        item.actualOutpicArea ? '' : item.actualOutpicArea = 0
        item.assortCustomizedArea ? '' : item.assortCustomizedArea = 0
        item.seriesOutpicArea ? '' : item.seriesOutpicArea = 0
        if (finished.includes(item.areaCode)) {
          item.seriesEdit = true
        }
        item.acceptId ? '' : item.acceptId = this.$route.query.id
        if (!item._key) {
          item._key = (Math.floor(Math.random() * 0xfffff)).toString()
        }
        t[key].push(item)
      }
      const result = []
      for (const v of Object.values(t)) {
        const len = v.length
        v.forEach((e, i) => {
          if (i === 0) {
            e.rowSpan = len
          } else {
            e.rowSpan = 0
          }
          result.push(e)
        })
      }
      return result
    },
    tableRowKeyFun(row) {
      return row._key
    },
    // 选择区域
    changeHandle(v) {
      if (v.length === 0) return
      v = v.map(e => {
        return {
          acceptArea: 0, // 验收面积
          acceptDesc: '',	// 验收说明
          acceptId: this.$route.query.id,	// 门店验收ID
          acceptSeriesArea: 0,
          acceptSeriesDesc: '',
          actualOutpicArea: 0,
          areaName: e.areaName,
          assortCustomizedArea: 0,
          areaCode: e.areaCode,
          configProgramSeriesId: '',
          isConstRangeAccept: '',
          outpicDesc: '',
          programName: '',
          seriesName: '',
          seriesOutpicArea: 0,
          // 自带字段
          areaCode: e.areaCode,
          areaType: e.areaType,
          types: 0
        }
      })
      let t = deepClone(this.tableData)
      t.unshift(...v)
      t = t.map(e => {
        delete e.keyIndex
        return e
      })
      this.tableData = this.handlerData(t)
    },
    spanMethod({ row, column, rowIndex, columnIndex }) {
      const indexs = [2, 3, 4, 5]
      if (indexs.includes(columnIndex)) {
        if (row.rowSpan !== 0) {
          return [row.rowSpan, 1]
        } else {
          return [0, 0]
        }
      }
      // return [row.rowSpan, 1]
    },
    selectionChange(v) {
      this.selections = v
    },
    // 系列变化
    changeSeriesHandle(v) {
      if (v.length === 0) return
      const tmp = []
      for (const item of v) {
        if (this.validateRepetition(this.selections[0], item, true)) {
          this.$message.warning('同一个空间不能有重复的系列！')
          continue
        }
        const s = deepClone(this.selections[0])
        delete s.id
        this.$set(s, 'seriesCode', item.seriesCode)
        this.$set(s, 'seriesName', item.seriesName)
        this.$set(s, 'styleCode', item.styleCode)
        this.$set(s, 'styleName', item.styleName)
        this.$set(s, 'configProgramSeriesId', item.configProgramSeriesId)
        tmp.push(s)
      }
      let t = deepClone(this.tableData)
      t.unshift(...tmp)
      t = t.map(e => {
        delete e.keyIndex
        return e
      })
      this.tableData = this.handlerData(t)
    },
    removeHandle() {
      if (this.selections.length === 0) {
        this.$message.warning('请选择数据！')
        return
      }
      this.tableData = this.handlerData(this.tableData.filter(e => !this.selections.includes(e)))
      this.selections = []
    },
    // 获取详情
    getData() {
      const { id } = this.$route.query
      getUnSeriesByAccId(id).then(res => {
        this.tableData = this.handlerData(res.data)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.no-check-area{
  .area{
    & /deep/ .el-table__row{
      background-color: #fff !important;
    }
    & /deep/ .hover-row{
      background-color: #fff !important;
    }
    & /deep/ td{
      background-color: #fff !important;
    }
  }
}
</style>
